package us.codecraft.webmagic.utils;

import com.alibaba.fastjson.JSON;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.TbkItemCouponGetRequest;
import com.taobao.api.request.TbkItemGetRequest;
import com.taobao.api.response.TbkItemCouponGetResponse;
import com.taobao.api.response.TbkItemGetResponse;
import us.codecraft.webmagic.config.Config;

/**
 * @描述： 淘宝客调工具类
 * @作者： Haiwei.Zhang
 * @创建时间： 2017-09-27
 * @版本： 1.0
 */
public class APIUtils {

    private static String url = Config.TAOBAO_URL;
    private static String appkey = Config.APP_KEY;
    private static String secret = Config.APP_SECRET;

    public static TaobaoClient doPost()  {
        TaobaoClient client = new DefaultTaobaoClient(url, appkey, secret);
       return client;
    }

    /**
     * 根据传入参数的的Class不同查询不同的API接口
     * 具体的参数查看FreeTaobaoAPIEnum类
     * @return
     */
    public static TbkItemGetResponse itemGetDemo(String cat){
        TbkItemGetRequest request = new TbkItemGetRequest();
        request.setFields("num_iid,title,pict_url,small_images,reserve_price,zk_final_price,user_type,provcity,item_url,seller_id,volume,nick");
        request.setCat(cat);
        request.setPageSize(1L);
        request.setPageNo(1L);
        try {
            return doPost().execute(request);
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 根据传入参数的的Class不同查询不同的API接口
     * 具体的参数查看FreeTaobaoAPIEnum类
     * @return
     */
    public static TbkItemGetResponse itemGetDemo(String cat,Long pageNo){
        TbkItemGetRequest request = new TbkItemGetRequest();
        request.setFields("num_iid,title,pict_url,small_images,reserve_price,zk_final_price,user_type,provcity,item_url,seller_id,volume,nick");
        request.setCat(cat);
        request.setPageSize(100L);
        request.setPageNo(pageNo);
        try {
            return doPost().execute(request);
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static TbkItemCouponGetResponse itemCat(String catName){
        TbkItemCouponGetRequest req = new TbkItemCouponGetRequest();
        req.setQ(catName);
        req.setPageSize(1L);
        req.setPageNo(1L);
        req.setPid("mm_126439157_37214046_134430735");
        TbkItemCouponGetResponse response = null;
        try {
            response = doPost().execute(req);
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return response;
    }

    public static void main(String[] args) {
        System.out.println(itemGetDemo("1512"));
        System.out.println(JSON.toJSONString(itemCat("111111")));
    }
}
